import { loginApi, getInfoApi, getDetaiUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      // 存入state
      state.token = data
      // 存入cookie实现数据持久化
      setToken(data)
    },
    // 删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户资料
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除用户资料
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 发请求的action
    async loginAction(context, data) {
      // 发请求
      const res = await loginApi(data)
      // 触发mutations
      context.commit('setToken', res)
    },
    // 获取用户资料的action
    async getUserInfoAction(context) {
      const res = await getInfoApi()
      // console.log(res)
      const res2 = await getDetaiUserInfoApi(res.userId)
      // 触发mutation
      context.commit('setUserInfo', { ...res, ...res2 })
    },
    // 退出操作
    quitAction(context) {
      // 清除token
      context.commit('removeToken')
      // 清除用户资料
      context.commit('removeUserInfo')
    }
  }
}
